package cn.iocoder.an.module.business.service.maintenanceinformation;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.an.module.business.controller.admin.equipmentmanage.vo.ImportRespVO;
import cn.iocoder.an.module.business.dal.dataobject.equipmentmanage.EquipmentManageDO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.micrometer.common.util.StringUtils;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

import cn.iocoder.an.module.business.controller.admin.maintenanceinformation.vo.*;
import cn.iocoder.an.module.business.dal.dataobject.maintenanceinformation.MaintenanceInformationDO;
import cn.iocoder.an.framework.common.pojo.PageResult;
import cn.iocoder.an.framework.common.pojo.PageParam;
import cn.iocoder.an.framework.common.util.object.BeanUtils;

import cn.iocoder.an.module.business.dal.mysql.maintenanceinformation.MaintenanceInformationMapper;

import static cn.iocoder.an.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.an.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.an.framework.common.util.collection.CollectionUtils.diffList;
import static cn.iocoder.an.module.business.enums.ErrorCodeConstants.*;

/**
 * 维保商档案 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class MaintenanceInformationServiceImpl implements MaintenanceInformationService {

    @Resource
    private MaintenanceInformationMapper maintenanceInformationMapper;

    @Override
    public Long createMaintenanceInformation(MaintenanceInformationSaveReqVO createReqVO) {
        // 插入
        MaintenanceInformationDO maintenanceInformation = BeanUtils.toBean(createReqVO, MaintenanceInformationDO.class);
        maintenanceInformationMapper.insert(maintenanceInformation);

        // 返回
        return maintenanceInformation.getId();
    }

    @Override
    public void updateMaintenanceInformation(MaintenanceInformationSaveReqVO updateReqVO) {
        // 校验存在
        validateMaintenanceInformationExists(updateReqVO.getId());
        // 更新
        MaintenanceInformationDO updateObj = BeanUtils.toBean(updateReqVO, MaintenanceInformationDO.class);
        maintenanceInformationMapper.updateById(updateObj);
    }

    @Override
    public void deleteMaintenanceInformation(Long id) {
        // 校验存在
        validateMaintenanceInformationExists(id);
        // 删除
        maintenanceInformationMapper.deleteById(id);
    }

    @Override
        public void deleteMaintenanceInformationListByIds(List<Long> ids) {
        // 删除
        maintenanceInformationMapper.deleteByIds(ids);
        }


    private void validateMaintenanceInformationExists(Long id) {
        if (maintenanceInformationMapper.selectById(id) == null) {
            throw exception(MAINTENANCE_INFORMATION_NOT_EXISTS);
        }
    }

    @Override
    public MaintenanceInformationDO getMaintenanceInformation(Long id) {
        return maintenanceInformationMapper.selectById(id);
    }

    @Override
    public PageResult<MaintenanceInformationDO> getMaintenanceInformationPage(MaintenanceInformationPageReqVO pageReqVO) {
        return maintenanceInformationMapper.selectPage(pageReqVO);
    }

    @Override
    public ImportRespVO importDataList(List<MaintenanceInfoImportExcelVO> importData, boolean isUpdateSupport) {
        // 1.1 参数校验
        if (CollUtil.isEmpty(importData)) {
            throw exception(IMPORT_EQUIPMENT_MANAGE_NOT_EXISTS);
        }

        //2.记录成功或失败记录
        ImportRespVO respVO = ImportRespVO.builder().insertNameList(new ArrayList<>())
                .updateNameList(new ArrayList<>()).failureMap(new LinkedHashMap<>()).build();

        AtomicInteger count = new AtomicInteger(1);
        importData.forEach(equipment -> {
            count.incrementAndGet();//记录行号

            // 2.1.1 校验企业名称
            if (StringUtils.isEmpty(equipment.getEnterpriseName())) {
                respVO.getFailureMap().put("第" + count + "行数据有误", "企业名称不能为空!");
                return;
            }

            // 2.1.2 校验状态
            if (equipment.getStatus() == null) {
                respVO.getFailureMap().put("第" + count + "行数据有误", "状态不能为空!");
                return;
            }

            // 2.2.6 判断是否存在，再进行更新或插入

            //判断信用代码有无重复
            String code = equipment.getCreditCode();
            MaintenanceInformationDO exists = maintenanceInformationMapper.selectFirstOne(
                    MaintenanceInformationDO::getCreditCode, code
            );

            if (exists != null ){
                //如果存在 判断是否允许更新
                if (isUpdateSupport) {
                    //允许更新
                    //设置ID
                    equipment.setId(exists.getId());
                    MaintenanceInformationDO updateObj = BeanUtils.toBean(equipment, MaintenanceInformationDO.class);
                    maintenanceInformationMapper.updateById(updateObj);
                    respVO.getUpdateNameList().add(equipment.getEnterpriseName());
                }else {
                    //重复且不允许更新 标识为失败
                    respVO.getFailureMap().put(equipment.getEnterpriseName(), EQUIPMENT_EXISTS.getMsg());
                }
            }else{
                //不存在 插入
                maintenanceInformationMapper.insert(BeanUtils.toBean(equipment, MaintenanceInformationDO.class));
                respVO.getInsertNameList().add(equipment.getEnterpriseName());
            }
        });
        return respVO;
    }

}